﻿using System;
using System.Windows;
using System.Windows.Input;

namespace GiveAQuiz.Common
{
  /// <summary>
  /// Used to wrap a UIElement to support double clicking.
  /// </summary>
  public class DoubleClickWrapper : IDisposable
  {
    UIElement _source = null;
    Action<UIElement> _callback = null;
    long _lastClickTime = 0;
    
    public DoubleClickWrapper(UIElement source, Action<UIElement> callback)
    {
      _source = source;
      _callback = callback;

      Initialize();
    }

    protected virtual void Initialize()
    {
      _source.MouseLeftButtonUp += new MouseButtonEventHandler(source_MouseLeftButtonUp);
      _source.MouseLeftButtonDown += new MouseButtonEventHandler(source_MouseLeftButtonDown);
    }

    void source_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      var clickTime = DateTime.Now.Ticks;

      // If the time between is less than 100 ms then doubleclick
      if (clickTime  - _lastClickTime < (100 * 10000)) // 100ms * 10000 ticks per ms
      {
        _callback(_source);
      }
    }

    void source_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
      // On every release, check the time
      _lastClickTime = DateTime.Now.Ticks;
    }

    public void Dispose()
    {
      _source.MouseLeftButtonUp -= new MouseButtonEventHandler(source_MouseLeftButtonUp);
      _source.MouseLeftButtonDown -= new MouseButtonEventHandler(source_MouseLeftButtonDown);
    }
  }
}
